package com.yfp.common.core.utils;


import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.yfp.common.core.constant.SmsConstants;
import com.yfp.common.core.enums.SmsTypeEnum;
import com.yfp.common.core.exception.ServiceException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Random;

@Slf4j
@Component
@Data
public class AliYunSmsUtils {


    private Random random = new Random();

    /**
     * 发送短信
     *
     * @return {@link SendSmsResponse}
     * @throws ClientException 客户端异常
     */
    private static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(SmsConstants.ACCESS_KEY_ID)
                .setAccessKeySecret(SmsConstants.ACCESS_KEY_SECRET);
        config.endpoint = SmsConstants.DOMAIN;
        return new Client(config);
    }

    private static void send(String phone, String jsonStr, String smsCode) {
        try {
            log.info("阿里云短信发送,手机：{}，内容：{}，模板：{}", phone, jsonStr, smsCode);
            Client client = AliYunSmsUtils.createClient();
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new SendSmsRequest().setSignName(SmsConstants.SIGN).setTemplateCode(smsCode)
                    .setPhoneNumbers(phone)
                    .setTemplateParam(jsonStr);
            SendSmsResponseBody body = client.sendSms(sendSmsRequest).getBody();
            if (!"OK".equals(body.getCode())) {
                log.error("阿里云短信发送失败，短信模板：{}，错误原因：{},手机号：{},内容：{}", smsCode, body.getMessage(), phone, jsonStr);
            }
        } catch (Exception e) {
            log.error("阿里云短信发送失败，短信模板：{}，错误原因：{},手机号：{},内容：{}", smsCode, e.getMessage(), phone, jsonStr);
            throw new ServiceException("短信发送失败,请稍后再试");
        }
    }

    //注册登录验证码发送
    public String sendVerifyCode(String phone) {
        String code = verificationCode(4);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        send(phone, jsonObject.toJSONString(), SmsTypeEnum.CURRENCY.getType());
        return code;
    }

    public String verificationCode(int size) {
        StringBuilder bld = new StringBuilder();
        for (int i = 0; i < size; i++) {
            bld.append(this.random.nextInt(10));
        }
        return bld.toString();
    }


}